<?php
/**
 * 图片主要（三通道）颜色判断
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/3/7
 * Time: 16:11
 */
namespace haibao\jiepai\common;
class ImageColor
{
    public static function imgColor($imgUrl)
    {
        $imageInfo = getimagesize($imgUrl);
        //图片类型
        $imgType = strtolower(substr(image_type_to_extension($imageInfo[2]), 1));
        //对应函数
        $imageFun = 'imagecreatefrom' . ($imgType == 'jpg' ? 'jpeg' : $imgType);
        $i = $imageFun($imgUrl);
        //循环色值
        $rColorNum = $gColorNum = $bColorNum = $total = 0;
        for ($x = 0; $x < imagesx($i); $x++) {
            for ($y = 0; $y < imagesy($i); $y++) {
                $rgb = imagecolorat($i, $x, $y);
                //三通道
                $r = ($rgb >> 16) & 0xFF;
                $g = ($rgb >> 8) & 0xFF;
                $b = $rgb & 0xFF;

                $rColorNum += $r;
                $gColorNum += $g;
                $bColorNum += $b;
                $total++;
            }
        }
        $rgb = array();
        $rgb['R'] = round($rColorNum / $total);
        $rgb['G'] = round($gColorNum / $total);
        $rgb['B'] = round($bColorNum / $total);
        return $rgb;
    }

    /*
     *RGB TO HEX
     *author cuitengwei
     *2014/1/16
     */
    public static function rgb2html($r, $g = -1, $b = -1)
    {
        if (is_array($r) && sizeof($r) == 3)
            list($r, $g, $b) = $r;

        $r = intval($r);
        $g = intval($g);
        $b = intval($b);

        $r = dechex($r < 0 ? 0 : ($r > 255 ? 255 : $r));
        $g = dechex($g < 0 ? 0 : ($g > 255 ? 255 : $g));
        $b = dechex($b < 0 ? 0 : ($b > 255 ? 255 : $b));

        $color = (strlen($r) < 2 ? '0' : '') . $r;
        $color .= (strlen($g) < 2 ? '0' : '') . $g;
        $color .= (strlen($b) < 2 ? '0' : '') . $b;
        return '#' . $color;
    }

    /*
     *HEX TO RGB
     *author cuitengwei
     *2014/1/16
     */
    public static function html2rgb($color)
    {
        if ($color[0] == '#')
            $color = substr($color, 1);

        if (strlen($color) == 6)
            list($r, $g, $b) = array($color[0] . $color[1],
                $color[2] . $color[3],
                $color[4] . $color[5]);
        elseif (strlen($color) == 3)
            list($r, $g, $b) = array($color[0] . $color[0], $color[1] . $color[1], $color[2] . $color[2]);
        else
            return false;

        $r = hexdec($r);
        $g = hexdec($g);
        $b = hexdec($b);

        return array($r, $g, $b);
    }
}